<?php

namespace app\api\model;

use app\common\model\BaseModel;

class NeedQuestion extends BaseModel
{
    public function language()
    {
        return $this->hasOne(Language::class, 'language_id', 'language_id');
    }

    /**
     * 获取用户需求问卷
     */
    public static function getByUserId($languageId, $userId)
    {
        return self::where('language_id', $languageId)->where('user_id', $userId)->find();
    }

    /**
     * 生成需求问卷
     */
    public function add(array $data)
    {
        return $this->allowField(true)->save($data);
    }

    /**
     * 编辑需求问卷
     */
    public function edit(array $data)
    {
        return $this->allowField(true)->save($data);
    }


    public static function getAllByUserId($userId)
    {
        return self::with('language')->where('user_id', $userId)->select();
    }

    /**
     * 用户需求
     * @param $userId
     * @return bool|false|\PDOStatement|string|\think\Collection
     */
    public static function getUserNeed($userId)
    {
        $need = self::getAllByUserId($userId);
        foreach ($need as $val) {
            $titles = json_decode($val['title'], true);
            $content = array_reduce(self::needResult($titles), 'array_merge', array());
            $val['title'] = $titles;
            $val['content'] = $content;
        }
        return $need;
    }

    /**
     * 需求答案
     */
    public static function needResult($titles)
    {
        $contents = [];
        foreach ($titles as $key=>$val) {
//            $question = Question::find($key);
            if (!is_array($val)) {
                $val = explode(',', $val);
            }
            $questionBank = QuestionBank::getInQuestionBankId($val);
            $content = array_column($questionBank, 'content');
            $contents[] = $content;
        }
        return $contents;
    }

    public static function getColumnByUserId($userId, $column)
    {
        return self::where('user_id', $userId)->column($column);
    }

}
